package channel;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;

/**
 *
 * @author Michael Hanns
 *
 */
public class ChannelMasterComms extends Thread {

    private boolean communicating;
    private InetAddress ip;
    private Socket channelSocket;
    private PrintWriter out;
    private BufferedReader in;

    private ArrayList<ChannelItem> sockets;

    private String motd;

    public ChannelMasterComms() {
        super();
        this.motd = "";
    }

    public String connectToMaster(String finalIP, String chanDets, ArrayList<ChannelItem> socks) {
        try {
            sockets = socks;
            ip = InetAddress.getByName(finalIP);

            channelSocket = new Socket(ip, 725);

            out = new PrintWriter(channelSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(channelSocket.getInputStream()));

            out.println("ADDCHANNEL " + chanDets);

            String input = in.readLine();

            communicating = Boolean.parseBoolean(input);

            if (communicating) {
                return "You are connected to " + finalIP + ".";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "You were unable to connect to " + finalIP + ".";
    }

    public void setMOTD(String motd) {
        this.motd = motd;
    }

    @Override
    public void run() {
        while (communicating) {
            try {
                Thread.sleep(25000);
                out.println("SETSERVERS " + sockets.size());
                out.println("SETMOTD " + motd);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void stopCommunicating() {
        if(communicating) {
            communicating = false;
        }
    }

    public boolean isCommunicating() {
        return communicating;
    }
}
